home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / test / test_support.pyc (.txt) < prev   
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  29.6 KB  |  874 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Supporting definitions for the Python regression tests.'''
  5. if __name__ != 'test.test_support':
  6.     raise ImportError('test_support must be imported from the test package')
  7. __name__ != 'test.test_support'
  8. import contextlib
  9. import errno
  10. import socket
  11. import sys
  12. import os
  13. import shutil
  14. import warnings
  15. import unittest
  16. __all__ = [
  17.     'Error',
  18.     'TestFailed',
  19.     'TestSkipped',
  20.     'ResourceDenied',
  21.     'import_module',
  22.     'verbose',
  23.     'use_resources',
  24.     'max_memuse',
  25.     'record_original_stdout',
  26.     'get_original_stdout',
  27.     'unload',
  28.     'unlink',
  29.     'rmtree',
  30.     'forget',
  31.     'is_resource_enabled',
  32.     'requires',
  33.     'find_unused_port',
  34.     'bind_port',
  35.     'fcmp',
  36.     'have_unicode',
  37.     'is_jython',
  38.     'TESTFN',
  39.     'HOST',
  40.     'FUZZ',
  41.     'findfile',
  42.     'verify',
  43.     'vereq',
  44.     'sortdict',
  45.     'check_syntax_error',
  46.     'open_urlresource',
  47.     'check_warnings',
  48.     'CleanImport',
  49.     'EnvironmentVarGuard',
  50.     'captured_output',
  51.     'captured_stdout',
  52.     'TransientResource',
  53.     'transient_internet',
  54.     'run_with_locale',
  55.     'set_memlimit',
  56.     'bigmemtest',
  57.     'bigaddrspacetest',
  58.     'BasicTestRunner',
  59.     'run_unittest',
  60.     'run_doctest',
  61.     'threading_setup',
  62.     'threading_cleanup',
  63.     'reap_children']
  64.  
  65. class Error(Exception):
  66.     '''Base class for regression test exceptions.'''
  67.     pass
  68.  
  69.  
  70. class TestFailed(Error):
  71.     '''Test failed.'''
  72.     pass
  73.  
  74.  
  75. class TestSkipped(Error):
  76.     """Test skipped.
  77.  
  78.     This can be raised to indicate that a test was deliberatly
  79.     skipped, but not because a feature wasn't available.  For
  80.     example, if some resource can't be used, such as the network
  81.     appears to be unavailable, this should be raised instead of
  82.     TestFailed.
  83.     """
  84.     pass
  85.  
  86.  
  87. class ResourceDenied(TestSkipped):
  88.     '''Test skipped because it requested a disallowed resource.
  89.  
  90.     This is raised when a test calls requires() for a resource that
  91.     has not be enabled.  It is used to distinguish between expected
  92.     and unexpected skips.
  93.     '''
  94.     pass
  95.  
  96.  
  97. def import_module(name, deprecated = False):
  98.     '''Import the module to be tested, raising TestSkipped if it is not
  99.     available.'''
  100.     warnings.catch_warnings().__enter__()
  101.     
  102.     try:
  103.         
  104.         try:
  105.             module = __import__(name, level = 0)
  106.         except ImportError:
  107.             None if deprecated else warnings.catch_warnings()
  108.             None if deprecated else warnings.catch_warnings()
  109.             raise TestSkipped('No module named ' + name)
  110.         except:
  111.             None if deprecated else warnings.catch_warnings()
  112.  
  113.         return module
  114.     finally:
  115.         pass
  116.  
  117.  
  118. verbose = 1
  119. use_resources = None
  120. max_memuse = 0
  121. real_max_memuse = 0
  122. _original_stdout = None
  123.  
  124. def record_original_stdout(stdout):
  125.     global _original_stdout
  126.     _original_stdout = stdout
  127.  
  128.  
  129. def get_original_stdout():
  130.     if not _original_stdout:
  131.         pass
  132.     return sys.stdout
  133.  
  134.  
  135. def unload(name):
  136.     
  137.     try:
  138.         del sys.modules[name]
  139.     except KeyError:
  140.         pass
  141.  
  142.  
  143.  
  144. def unlink(filename):
  145.     
  146.     try:
  147.         os.unlink(filename)
  148.     except OSError:
  149.         pass
  150.  
  151.  
  152.  
  153. def rmtree(path):
  154.     
  155.     try:
  156.         shutil.rmtree(path)
  157.     except OSError:
  158.         e = None
  159.         if e.errno not in (errno.ENOENT, errno.ESRCH):
  160.             raise 
  161.         e.errno not in (errno.ENOENT, errno.ESRCH)
  162.  
  163.  
  164.  
  165. def forget(modname):
  166.     '''"Forget" a module was ever imported by removing it from sys.modules and
  167.     deleting any .pyc and .pyo files.'''
  168.     unload(modname)
  169.     for dirname in sys.path:
  170.         unlink(os.path.join(dirname, modname + os.extsep + 'pyc'))
  171.         unlink(os.path.join(dirname, modname + os.extsep + 'pyo'))
  172.     
  173.  
  174.  
  175. def is_resource_enabled(resource):
  176.     '''Test whether a resource is enabled.  Known resources are set by
  177.     regrtest.py.'''
  178.     if use_resources is not None:
  179.         pass
  180.     return resource in use_resources
  181.  
  182.  
  183. def requires(resource, msg = None):
  184.     """Raise ResourceDenied if the specified resource is not available.
  185.  
  186.     If the caller's module is __main__ then automatically return True.  The
  187.     possibility of False being returned occurs when regrtest.py is executing."""
  188.     if sys._getframe().f_back.f_globals.get('__name__') == '__main__':
  189.         return None
  190.     if not is_resource_enabled(resource):
  191.         if msg is None:
  192.             msg = "Use of the `%s' resource not enabled" % resource
  193.         
  194.         raise ResourceDenied(msg)
  195.     is_resource_enabled(resource)
  196.  
  197. HOST = 'localhost'
  198.  
  199. def find_unused_port(family = socket.AF_INET, socktype = socket.SOCK_STREAM):
  200.     """Returns an unused port that should be suitable for binding.  This is
  201.     achieved by creating a temporary socket with the same family and type as
  202.     the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
  203.     the specified host address (defaults to 0.0.0.0) with the port set to 0,
  204.     eliciting an unused ephemeral port from the OS.  The temporary socket is
  205.     then closed and deleted, and the ephemeral port is returned.
  206.  
  207.     Either this method or bind_port() should be used for any tests where a
  208.     server socket needs to be bound to a particular port for the duration of
  209.     the test.  Which one to use depends on whether the calling code is creating
  210.     a python socket, or if an unused port needs to be provided in a constructor
  211.     or passed to an external program (i.e. the -accept argument to openssl's
  212.     s_server mode).  Always prefer bind_port() over find_unused_port() where
  213.     possible.  Hard coded ports should *NEVER* be used.  As soon as a server
  214.     socket is bound to a hard coded port, the ability to run multiple instances
  215.     of the test simultaneously on the same host is compromised, which makes the
  216.     test a ticking time bomb in a buildbot environment. On Unix buildbots, this
  217.     may simply manifest as a failed test, which can be recovered from without
  218.     intervention in most cases, but on Windows, the entire python process can
  219.     completely and utterly wedge, requiring someone to log in to the buildbot
  220.     and manually kill the affected process.
  221.  
  222.     (This is easy to reproduce on Windows, unfortunately, and can be traced to
  223.     the SO_REUSEADDR socket option having different semantics on Windows versus
  224.     Unix/Linux.  On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
  225.     listen and then accept connections on identical host/ports.  An EADDRINUSE
  226.     socket.error will be raised at some point (depending on the platform and
  227.     the order bind and listen were called on each socket).
  228.  
  229.     However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
  230.     will ever be raised when attempting to bind two identical host/ports. When
  231.     accept() is called on each socket, the second caller's process will steal
  232.     the port from the first caller, leaving them both in an awkwardly wedged
  233.     state where they'll no longer respond to any signals or graceful kills, and
  234.     must be forcibly killed via OpenProcess()/TerminateProcess().
  235.  
  236.     The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
  237.     instead of SO_REUSEADDR, which effectively affords the same semantics as
  238.     SO_REUSEADDR on Unix.  Given the propensity of Unix developers in the Open
  239.     Source world compared to Windows ones, this is a common mistake.  A quick
  240.     look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
  241.     openssl.exe is called with the 's_server' option, for example. See
  242.     http://bugs.python.org/issue2550 for more info.  The following site also
  243.     has a very thorough description about the implications of both REUSEADDR
  244.     and EXCLUSIVEADDRUSE on Windows:
  245.     http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)
  246.  
  247.     XXX: although this approach is a vast improvement on previous attempts to
  248.     elicit unused ports, it rests heavily on the assumption that the ephemeral
  249.     port returned to us by the OS won't immediately be dished back out to some
  250.     other process when we close and delete our temporary socket but before our
  251.     calling code has a chance to bind the returned port.  We can deal with this
  252.     issue if/when we come across it."""
  253.     tempsock = socket.socket(family, socktype)
  254.     port = bind_port(tempsock)
  255.     tempsock.close()
  256.     del tempsock
  257.     return port
  258.  
  259.  
  260. def bind_port(sock, host = HOST):
  261.     """Bind the socket to a free port and return the port number.  Relies on
  262.     ephemeral ports in order to ensure we are using an unbound port.  This is
  263.     important as many tests may be running simultaneously, especially in a
  264.     buildbot environment.  This method raises an exception if the sock.family
  265.     is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
  266.     or SO_REUSEPORT set on it.  Tests should *never* set these socket options
  267.     for TCP/IP sockets.  The only case for setting these options is testing
  268.     multicasting via multiple UDP sockets.
  269.  
  270.     Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
  271.     on Windows), it will be set on the socket.  This will prevent anyone else
  272.     from bind()'ing to our host/port for the duration of the test.
  273.     """
  274.     if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
  275.         if hasattr(socket, 'SO_REUSEADDR'):
  276.             if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
  277.                 raise TestFailed('tests should never set the SO_REUSEADDR socket option on TCP/IP sockets!')
  278.             sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1
  279.         
  280.         if hasattr(socket, 'SO_REUSEPORT'):
  281.             if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
  282.                 raise TestFailed('tests should never set the SO_REUSEPORT socket option on TCP/IP sockets!')
  283.             sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1
  284.         
  285.         if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
  286.             sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
  287.         
  288.     
  289.     sock.bind((host, 0))
  290.     port = sock.getsockname()[1]
  291.     return port
  292.  
  293. FUZZ = 1e-06
  294.  
  295. def fcmp(x, y):
  296.     if isinstance(x, float) or isinstance(y, float):
  297.         
  298.         try:
  299.             fuzz = (abs(x) + abs(y)) * FUZZ
  300.             if abs(x - y) <= fuzz:
  301.                 return 0
  302.  
  303.     elif type(x) == type(y) and isinstance(x, (tuple, list)):
  304.         for i in range(min(len(x), len(y))):
  305.             outcome = fcmp(x[i], y[i])
  306.             if outcome != 0:
  307.                 return outcome
  308.         
  309.         return (len(x) > len(y)) - (len(x) < len(y))
  310.     outcome != 0
  311.     return (x > y) - (x < y)
  312.  
  313.  
  314. try:
  315.     unicode
  316.     have_unicode = True
  317. except NameError:
  318.     have_unicode = False
  319.  
  320. is_jython = sys.platform.startswith('java')
  321. if os.name == 'java':
  322.     TESTFN = '$test'
  323. elif os.name == 'riscos':
  324.     TESTFN = 'testfile'
  325. else:
  326.     TESTFN = '@test'
  327.     if have_unicode:
  328.         if isinstance('', unicode):
  329.             TESTFN_UNICODE = '@test-\xe0\xf2'
  330.         else:
  331.             TESTFN_UNICODE = unicode('@test-\xe0\xf2', 'latin-1')
  332.         TESTFN_ENCODING = sys.getfilesystemencoding()
  333.         if not hasattr(sys, 'getwindowsversion') or sys.getwindowsversion()[3] < 2:
  334.             TESTFN_UNICODE_UNENCODEABLE = None
  335.         else:
  336.             TESTFN_UNICODE_UNENCODEABLE = eval('u"@test-\\u5171\\u6709\\u3055\\u308c\\u308b"')
  337.             
  338.             try:
  339.                 TESTFN_UNICODE_UNENCODEABLE.encode('Latin1')
  340.             except UnicodeEncodeError:
  341.                 pass
  342.  
  343.             print 'WARNING: The filename %r CAN be encoded by the filesystem.  Unicode filename tests may not be effective' % TESTFN_UNICODE_UNENCODEABLE
  344.     
  345. fp = None
  346.  
  347. try:
  348.     fp = open(TESTFN, 'w+')
  349. except IOError:
  350.     TMP_TESTFN = os.path.join('/tmp', TESTFN)
  351.     
  352.     try:
  353.         fp = open(TMP_TESTFN, 'w+')
  354.         TESTFN = TMP_TESTFN
  355.         del TMP_TESTFN
  356.     except IOError:
  357.         print 'WARNING: tests will fail, unable to write to: %s or %s' % (TESTFN, TMP_TESTFN)
  358.     except:
  359.         None<EXCEPTION MATCH>IOError
  360.     
  361.  
  362.     None<EXCEPTION MATCH>IOError
  363.  
  364. if fp is not None:
  365.     fp.close()
  366.     unlink(TESTFN)
  367.  
  368. del fp
  369.  
  370. def findfile(file, here = __file__):
  371.     '''Try to find a file on sys.path and the working directory.  If it is not
  372.     found the argument passed to the function is returned (this does not
  373.     necessarily signal failure; could still be the legitimate path).'''
  374.     if os.path.isabs(file):
  375.         return file
  376.     path = sys.path
  377.     path = [
  378.         os.path.dirname(here)] + path
  379.     for dn in path:
  380.         fn = os.path.join(dn, file)
  381.         if os.path.exists(fn):
  382.             return fn
  383.     
  384.     return file
  385.  
  386.  
  387. def verify(condition, reason = 'test failed'):
  388.     '''Verify that condition is true. If not, raise TestFailed.
  389.  
  390.        The optional argument reason can be given to provide
  391.        a better error text.
  392.     '''
  393.     if not condition:
  394.         raise TestFailed(reason)
  395.     condition
  396.  
  397.  
  398. def vereq(a, b):
  399.     '''Raise TestFailed if a == b is false.
  400.  
  401.     This is better than verify(a == b) because, in case of failure, the
  402.     error message incorporates repr(a) and repr(b) so you can see the
  403.     inputs.
  404.  
  405.     Note that "not (a == b)" isn\'t necessarily the same as "a != b"; the
  406.     former is tested.
  407.     '''
  408.     if not a == b:
  409.         raise TestFailed('%r == %r' % (a, b))
  410.     a == b
  411.  
  412.  
  413. def sortdict(dict):
  414.     '''Like repr(dict), but in sorted order.'''
  415.     items = dict.items()
  416.     items.sort()
  417.     reprpairs = [ '%r: %r' % pair for pair in items ]
  418.     withcommas = ', '.join(reprpairs)
  419.     return '{%s}' % withcommas
  420.  
  421.  
  422. def make_bad_fd():
  423.     '''
  424.     Create an invalid file descriptor by opening and closing a file and return
  425.     its fd.
  426.     '''
  427.     file = open(TESTFN, 'wb')
  428.     
  429.     try:
  430.         return file.fileno()
  431.     finally:
  432.         file.close()
  433.         unlink(TESTFN)
  434.  
  435.  
  436.  
  437. def check_syntax_error(testcase, statement):
  438.     
  439.     try:
  440.         compile(statement, '<test string>', 'exec')
  441.     except SyntaxError:
  442.         pass
  443.  
  444.     testcase.fail('Missing SyntaxError: "%s"' % statement)
  445.  
  446.  
  447. def open_urlresource(url):
  448.     import urllib
  449.     import urlparse
  450.     requires('urlfetch')
  451.     filename = urlparse.urlparse(url)[2].split('/')[-1]
  452.     for path in [
  453.         os.path.curdir,
  454.         os.path.pardir]:
  455.         fn = os.path.join(path, filename)
  456.         if os.path.exists(fn):
  457.             return open(fn)
  458.     
  459.     print >>get_original_stdout(), '\tfetching %s ...' % url
  460.     (fn, _) = urllib.urlretrieve(url, filename)
  461.     return open(fn)
  462.  
  463.  
  464. class WarningsRecorder(object):
  465.     '''Convenience wrapper for the warnings list returned on
  466.        entry to the warnings.catch_warnings() context manager.
  467.     '''
  468.     
  469.     def __init__(self, warnings_list):
  470.         self.warnings = warnings_list
  471.  
  472.     
  473.     def __getattr__(self, attr):
  474.         if self.warnings:
  475.             return getattr(self.warnings[-1], attr)
  476.         if attr in warnings.WarningMessage._WARNING_DETAILS:
  477.             return None
  478.         raise AttributeError('%r has no attribute %r' % (self, attr))
  479.  
  480.     
  481.     def reset(self):
  482.         del self.warnings[:]
  483.  
  484.  
  485.  
  486. def check_warnings():
  487.     
  488.     try:
  489.         w = _[1]
  490.         yield WarningsRecorder(w)
  491.         warnings.catch_warnings(record = True).__exit__
  492.     finally:
  493.         pass
  494.  
  495.  
  496. check_warnings = contextlib.contextmanager(check_warnings)
  497.  
  498. class CleanImport(object):
  499.     '''Context manager to force import to return a new module reference.
  500.  
  501.     This is useful for testing module-level behaviours, such as
  502.     the emission of a DeprecationWarning on import.
  503.  
  504.     Use like this:
  505.  
  506.         with CleanImport("foo"):
  507.             __import__("foo") # new reference
  508.     '''
  509.     
  510.     def __init__(self, *module_names):
  511.         self.original_modules = sys.modules.copy()
  512.         for module_name in module_names:
  513.             if module_name in sys.modules:
  514.                 module = sys.modules[module_name]
  515.                 if module.__name__ != module_name:
  516.                     del sys.modules[module.__name__]
  517.                 
  518.                 del sys.modules[module_name]
  519.                 continue
  520.         
  521.  
  522.     
  523.     def __enter__(self):
  524.         return self
  525.  
  526.     
  527.     def __exit__(self, *ignore_exc):
  528.         sys.modules.update(self.original_modules)
  529.  
  530.  
  531.  
  532. class EnvironmentVarGuard(object):
  533.     '''Class to help protect the environment variable properly.  Can be used as
  534.     a context manager.'''
  535.     
  536.     def __init__(self):
  537.         self._environ = os.environ
  538.         self._unset = set()
  539.         self._reset = dict()
  540.  
  541.     
  542.     def set(self, envvar, value):
  543.         if envvar not in self._environ:
  544.             self._unset.add(envvar)
  545.         else:
  546.             self._reset[envvar] = self._environ[envvar]
  547.         self._environ[envvar] = value
  548.  
  549.     
  550.     def unset(self, envvar):
  551.         if envvar in self._environ:
  552.             self._reset[envvar] = self._environ[envvar]
  553.             del self._environ[envvar]
  554.         
  555.  
  556.     
  557.     def __enter__(self):
  558.         return self
  559.  
  560.     
  561.     def __exit__(self, *ignore_exc):
  562.         for envvar, value in self._reset.iteritems():
  563.             self._environ[envvar] = value
  564.         
  565.         for unset in self._unset:
  566.             del self._environ[unset]
  567.         
  568.  
  569.  
  570.  
  571. class TransientResource(object):
  572.     '''Raise ResourceDenied if an exception is raised while the context manager
  573.     is in effect that matches the specified exception and attributes.'''
  574.     
  575.     def __init__(self, exc, **kwargs):
  576.         self.exc = exc
  577.         self.attrs = kwargs
  578.  
  579.     
  580.     def __enter__(self):
  581.         return self
  582.  
  583.     
  584.     def __exit__(self, type_ = None, value = None, traceback = None):
  585.         '''If type_ is a subclass of self.exc and value has attributes matching
  586.         self.attrs, raise ResourceDenied.  Otherwise let the exception
  587.         propagate (if any).'''
  588.         if type_ is not None and issubclass(self.exc, type_):
  589.             for attr, attr_value in self.attrs.iteritems():
  590.                 if not hasattr(value, attr):
  591.                     break
  592.                 
  593.                 if getattr(value, attr) != attr_value:
  594.                     break
  595.                     continue
  596.             else:
  597.                 raise ResourceDenied('an optional resource is not available')
  598.  
  599.  
  600.  
  601. def transient_internet():
  602.     '''Return a context manager that raises ResourceDenied when various issues
  603.     with the Internet connection manifest themselves as exceptions.'''
  604.     time_out = TransientResource(IOError, errno = errno.ETIMEDOUT)
  605.     socket_peer_reset = TransientResource(socket.error, errno = errno.ECONNRESET)
  606.     ioerror_peer_reset = TransientResource(IOError, errno = errno.ECONNRESET)
  607.     return contextlib.nested(time_out, socket_peer_reset, ioerror_peer_reset)
  608.  
  609.  
  610. def captured_output(stream_name):
  611.     '''Run the \'with\' statement body using a StringIO object in place of a
  612.     specific attribute on the sys module.
  613.     Example use (with \'stream_name=stdout\')::
  614.  
  615.        with captured_stdout() as s:
  616.            print "hello"
  617.        assert s.getvalue() == "hello"
  618.     '''
  619.     import StringIO
  620.     orig_stdout = getattr(sys, stream_name)
  621.     setattr(sys, stream_name, StringIO.StringIO())
  622.     
  623.     try:
  624.         yield getattr(sys, stream_name)
  625.     finally:
  626.         setattr(sys, stream_name, orig_stdout)
  627.  
  628.  
  629. captured_output = contextlib.contextmanager(captured_output)
  630.  
  631. def captured_stdout():
  632.     return captured_output('stdout')
  633.  
  634.  
  635. def run_with_locale(catstr, *locales):
  636.     
  637.     def decorator(func):
  638.         
  639.         def inner(*args, **kwds):
  640.             
  641.             try:
  642.                 import locale
  643.                 category = getattr(locale, catstr)
  644.                 orig_locale = locale.setlocale(category)
  645.             except AttributeError:
  646.                 raise 
  647.             except:
  648.                 locale = None
  649.                 orig_locale = None
  650.  
  651.             for loc in locales:
  652.                 
  653.                 try:
  654.                     locale.setlocale(category, loc)
  655.                 continue
  656.                 continue
  657.  
  658.             
  659.             
  660.             try:
  661.                 return func(*args, **kwds)
  662.             finally:
  663.                 if locale and orig_locale:
  664.                     locale.setlocale(category, orig_locale)
  665.                 
  666.  
  667.  
  668.         inner.func_name = func.func_name
  669.         inner.__doc__ = func.__doc__
  670.         return inner
  671.  
  672.     return decorator
  673.  
  674. _1M = 1048576
  675. _1G = 1024 * _1M
  676. _2G = 2 * _1G
  677. _4G = 4 * _1G
  678. MAX_Py_ssize_t = sys.maxsize
  679.  
  680. def set_memlimit(limit):
  681.     global real_max_memuse, max_memuse
  682.     import re
  683.     sizes = {
  684.         'k': 1024,
  685.         'm': _1M,
  686.         'g': _1G,
  687.         't': 1024 * _1G }
  688.     m = re.match('(\\d+(\\.\\d+)?) (K|M|G|T)b?$', limit, re.IGNORECASE | re.VERBOSE)
  689.     if m is None:
  690.         raise ValueError('Invalid memory limit %r' % (limit,))
  691.     m is None
  692.     memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
  693.     real_max_memuse = memlimit
  694.     if memlimit > MAX_Py_ssize_t:
  695.         memlimit = MAX_Py_ssize_t
  696.     
  697.     if memlimit < _2G - 1:
  698.         raise ValueError('Memory limit %r too low to be useful' % (limit,))
  699.     memlimit < _2G - 1
  700.     max_memuse = memlimit
  701.  
  702.  
  703. def bigmemtest(minsize, memuse, overhead = 5 * _1M):
  704.     """Decorator for bigmem tests.
  705.  
  706.     'minsize' is the minimum useful size for the test (in arbitrary,
  707.     test-interpreted units.) 'memuse' is the number of 'bytes per size' for
  708.     the test, or a good estimate of it. 'overhead' specifies fixed overhead,
  709.     independent of the testsize, and defaults to 5Mb.
  710.  
  711.     The decorator tries to guess a good value for 'size' and passes it to
  712.     the decorated test function. If minsize * memuse is more than the
  713.     allowed memory use (as defined by max_memuse), the test is skipped.
  714.     Otherwise, minsize is adjusted upward to use up to max_memuse.
  715.     """
  716.     
  717.     def decorator(f):
  718.         
  719.         def wrapper(self):
  720.             return f(self, maxsize)
  721.  
  722.         wrapper.minsize = minsize
  723.         wrapper.memuse = memuse
  724.         wrapper.overhead = overhead
  725.         return wrapper
  726.  
  727.     return decorator
  728.  
  729.  
  730. def precisionbigmemtest(size, memuse, overhead = 5 * _1M):
  731.     
  732.     def decorator(f):
  733.         
  734.         def wrapper(self):
  735.             return f(self, maxsize)
  736.  
  737.         wrapper.size = size
  738.         wrapper.memuse = memuse
  739.         wrapper.overhead = overhead
  740.         return wrapper
  741.  
  742.     return decorator
  743.  
  744.  
  745. def bigaddrspacetest(f):
  746.     '''Decorator for tests that fill the address space.'''
  747.     
  748.     def wrapper(self):
  749.         if max_memuse < MAX_Py_ssize_t:
  750.             if verbose:
  751.                 sys.stderr.write('Skipping %s because of memory constraint\n' % (f.__name__,))
  752.             
  753.         else:
  754.             return f(self)
  755.         return max_memuse < MAX_Py_ssize_t
  756.  
  757.     return wrapper
  758.  
  759.  
  760. class BasicTestRunner:
  761.     
  762.     def run(self, test):
  763.         result = unittest.TestResult()
  764.         test(result)
  765.         return result
  766.  
  767.  
  768.  
  769. def _run_suite(suite):
  770.     '''Run tests from a unittest.TestSuite-derived class.'''
  771.     if verbose:
  772.         runner = unittest.TextTestRunner(sys.stdout, verbosity = 2)
  773.     else:
  774.         runner = BasicTestRunner()
  775.     result = runner.run(suite)
  776.     if not result.wasSuccessful():
  777.         if len(result.errors) == 1 and not (result.failures):
  778.             err = result.errors[0][1]
  779.         elif len(result.failures) == 1 and not (result.errors):
  780.             err = result.failures[0][1]
  781.         else:
  782.             err = 'errors occurred; run in verbose mode for details'
  783.         raise TestFailed(err)
  784.     result.wasSuccessful()
  785.  
  786.  
  787. def run_unittest(*classes):
  788.     '''Run tests from unittest.TestCase-derived classes.'''
  789.     valid_types = (unittest.TestSuite, unittest.TestCase)
  790.     suite = unittest.TestSuite()
  791.     for cls in classes:
  792.         if isinstance(cls, str):
  793.             if cls in sys.modules:
  794.                 suite.addTest(unittest.findTestCases(sys.modules[cls]))
  795.             else:
  796.                 raise ValueError('str arguments must be keys in sys.modules')
  797.         cls in sys.modules
  798.         if isinstance(cls, valid_types):
  799.             suite.addTest(cls)
  800.             continue
  801.         suite.addTest(unittest.makeSuite(cls))
  802.     
  803.     _run_suite(suite)
  804.  
  805.  
  806. def run_doctest(module, verbosity = None):
  807.     """Run doctest on the given module.  Return (#failures, #tests).
  808.  
  809.     If optional argument verbosity is not specified (or is None), pass
  810.     test_support's belief about verbosity on to doctest.  Else doctest's
  811.     usual behavior is used (it searches sys.argv for -v).
  812.     """
  813.     import doctest
  814.     if verbosity is None:
  815.         verbosity = verbose
  816.     else:
  817.         verbosity = None
  818.     save_stdout = sys.stdout
  819.     sys.stdout = get_original_stdout()
  820.     
  821.     try:
  822.         (f, t) = doctest.testmod(module, verbose = verbosity)
  823.         if f:
  824.             raise TestFailed('%d of %d doctests failed' % (f, t))
  825.         f
  826.     finally:
  827.         sys.stdout = save_stdout
  828.  
  829.     if verbose:
  830.         print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t)
  831.     
  832.     return (f, t)
  833.  
  834.  
  835. def threading_setup():
  836.     import threading
  837.     return (len(threading._active), len(threading._limbo))
  838.  
  839.  
  840. def threading_cleanup(num_active, num_limbo):
  841.     import threading
  842.     import time
  843.     _MAX_COUNT = 10
  844.     count = 0
  845.     while len(threading._active) != num_active and count < _MAX_COUNT:
  846.         count += 1
  847.         time.sleep(0.1)
  848.     count = 0
  849.     while len(threading._limbo) != num_limbo and count < _MAX_COUNT:
  850.         count += 1
  851.         time.sleep(0.1)
  852.  
  853.  
  854. def reap_children():
  855.     '''Use this function at the end of test_main() whenever sub-processes
  856.     are started.  This will help ensure that no extra children (zombies)
  857.     stick around to hog resources and create problems when looking
  858.     for refleaks.
  859.     '''
  860.     if hasattr(os, 'waitpid'):
  861.         any_process = -1
  862.         while True:
  863.             
  864.             try:
  865.                 (pid, status) = os.waitpid(any_process, os.WNOHANG)
  866.                 if pid == 0:
  867.                     break
  868.             continue
  869.             break
  870.             continue
  871.  
  872.     
  873.  
  874.